import EventManager from "../Common/EventManager";
import FMJava from "../Common/FMJava";
import Loader from "../Common/Loader";
import yyComponent from "../Common/yyComponent";
import { EventType } from "../GameSpecial/GameEventType";
import { GAME_MODE } from "../frameSccript/other/game/gameMode_Json";
import UserService from "../frameSccript/services/userService";
import UMe, { mgrs, sers } from "../frameSccript/system/OverallSystem ";
import RankMgr from "./RankMgr";
import ScrollViewExample from "./ScrollViewExample";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Home extends yyComponent {


    @property({ type: cc.Label, displayName: "定位显示Label" })
    dingweiLabel: cc.Label = null;

    @property({ type: RankMgr, displayName: "地区脚本 -- 用来获取地区排名的" })
    RankMgr: RankMgr = null;

    @property(cc.Node)
    scrollView: cc.Node = null;

    @property(cc.Label)
    gold:cc.Label = null

    onLoad() {

    }

    start() {
        sers().localStorageSrv.set("home-test", "hello-home-test");
        this.node.getComponent(cc.Canvas).fitHeight = UserService.IPAD
        this.node.getComponent(cc.Canvas).fitWidth = !UserService.IPAD

        if(window['tt']){
            var options = window['tt'].getLaunchOptionsSync();
            if('101001'==options.scene &&  !sers().userSrv.getCheckScene()){
                window['sceneCode'] = options.scene
                sers().uiSrv.showCebianlan()
            }
        }
        this.renewData()
        this.loadLevelScene()
        mgrs().soundMgr.playMusic('bgm');

        // this.guohe()
    //    this.startGame()

       this.updataGamelist()

        this.gold.string = sers().userSrv.coin +''

        
        this.scheduleOnce(()=>{
            if (this.node.height > 1400) {
                this.gold.node.parent.getComponent(cc.Widget).top = 90
                this.gold.node.parent.getComponent(cc.Widget).updateAlignment()
                
                this.node.getChildByName('setButton').getComponent(cc.Widget).top = 75
                this.node.getChildByName('setButton').getComponent(cc.Widget).updateAlignment()

                this.node.getChildByName('topLayer').getComponent(cc.Widget).top = 90
                this.node.getChildByName('topLayer').getComponent(cc.Widget).updateAlignment()

                this.node.getChildByName('xiaochuguize').getComponent(cc.Widget).top = 170
                this.node.getChildByName('xiaochuguize').getComponent(cc.Widget).updateAlignment()
                
            }
        })
        EventManager.on(EventType.UIEvent.SignInList,this.updataGold.bind(this),this)
        EventManager.on(EventType.UIEvent.updataGamelist,this.updataGamelist.bind(this),this)
        EventManager.on(EventType.DirectorEvent.updataGold, this.updataGold.bind(this), this)


        let nowTime =  new Date().getTime();
        let s = sers().userSrv.getSignInList()
        let can = false
        if(s.lastTime){
            can = this.isSameDay(nowTime, s.lastTime)
           
        }
    

        // if(!window['qiandao'] && !can && window['tt'] && window['wx']){
        //     this.qiandao()
        // }


        if(window['wx']){
            this.node.getChildByName('diqu').active = false
        }

        
        this.updataGold()
        sers().userSrv.setNowScene('home')
        // mgrs().gameMgr.enterMode(GAME_MODE.Fangkuai,true);
        // mgrs().gameMgr.enterMode(GAME_MODE.HechengDaxigua,true);
    }

    updataGamelist(){
        let game = sers().userSrv.getTiyanGame()
        if(this.node){
            // if(game.indexOf('guohe')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('guoheBtn').getChildByName('icon').active = false
            // }
            // if(game.indexOf('paidui')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('paiduiBtn').getChildByName('icon').active = false
            // }
    
            // if(game.indexOf('liushui')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('liushuiBtn').getChildByName('icon').active = false
            // }
    
            // if(game.indexOf('lingmajiang')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('lingmajiangBtn').getChildByName('icon').active = false
            // }

            // if(game.indexOf('HechengDaxigua')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('majianghechengBtn').getChildByName('icon').active = false
            // }
            // if(game.indexOf('Fangkuai')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            //     this.node.getChildByName('newBtn').getChildByName('icon').active = false
            // }
            
    
        }
       
    }

    isSameDay(timestamp1, timestamp2) {
        const date1 = new Date(timestamp1);
        const date2 = new Date(timestamp2);
      
        return (
          date1.getFullYear() === date2.getFullYear() &&
          date1.getMonth() === date2.getMonth() &&
          date1.getDate() === date2.getDate()
        );
      }

    updataGold(){
        // if(this && this.gold){
        //     this.gold.string = sers().userSrv.coin +''


        //     let nowTime =  new Date().getTime();
        //     let s = sers().userSrv.getSignInList()
        //     let can = false
        //     if(s.lastTime){
        //         can = this.isSameDay(nowTime, s.lastTime)
        //     }
            
        //      this.node.getChildByName('qiandaoBtn').getChildByName('hongdian').active = !can

        //      let zt = sers().userSrv.getZhutiData()
        //     this.node.getChildByName('pifuBtn').getChildByName('hongdian').active = zt.length<8? true:false

        // }
    }

    setBtn(){
        mgrs().soundMgr.playBtnSound();
        sers().uiSrv.showSettingPage();

    }

    openGengDuoWanfa() {
        mgrs().soundMgr.playBtnSound();
        sers().uiSrv.showGameListNewPage()
        
    }

    startGame(){

        // let diquName = sers().userSrv.getUserData().city
        // if ((diquName == null || diquName == '') && !window['showdiqu']) {
        //     sers().uiSrv.showSelectDiQuPage();
        //     window['showdiqu'] = true
        //     return;
        // }
        mgrs().soundMgr.playBtnSound();
        mgrs().gameMgr.enterMode(GAME_MODE.MAJIANG);
    }

    moreGame(){
        // sers().uiSrv.showMessage('敬请期待')
        mgrs().soundMgr.playBtnSound();
        // let UserData = sers().userSrv.getUserData()
        // if((window['tt']||window['wx']) && UserData.maxLevel<8){
        //     sers().uiSrv.showMessage('达到大师段位，解锁该模式')
        //     return 
        // }

        sers().uiSrv.showGameListPage()
        // mgrs().gameMgr.enterMode(GAME_MODE.MAJIANGLEVEL);
    }

    jieduanName = ['小白', '新手', '入门', '熟练', '精英', '高手', '专业', '大师', '宗师', '雀圣', '雀神']
    guohe(){
        mgrs().soundMgr.playBtnSound();

        // let UserData = sers().userSrv.getUserData()
        // if((window['tt']||window['wx']) && UserData.maxLevel<6){
        //     sers().uiSrv.showMessage(`达到${this.jieduanName[5]}段位，解锁该模式`)
        //     return 
        // }
        // mgrs().gameMgr.enterMode(GAME_MODE.MajiangGuohe,true);
        // return

        // mgrs().gameMgr.enterMode(GAME_MODE.MajiangGuohe);

        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('guohe')>=0){
            mgrs().gameMgr.enterMode(GAME_MODE.MajiangGuohe,true);
            
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('guohe')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('guoheBtn').getChildByName('icon').active = false
                mgrs().gameMgr.enterMode(GAME_MODE.MajiangGuohe,true);

            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁过河打麻将',
              },'common_video');
        }
        
       
    }

    paidui(){
        mgrs().soundMgr.playBtnSound();

        // let UserData = sers().userSrv.getUserData()
        // if((window['tt']||window['wx']) && UserData.maxLevel<8){
        //     sers().uiSrv.showMessage(`达到${this.jieduanName[7]}段位，解锁该模式`)
        //     return 
        // }

        // mgrs().gameMgr.enterMode(GAME_MODE.Paidui,true);
        // return

        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('paidui')>=0){

            if(sers().userSrv.power<=0){
                sers().uiSrv.showUserGetPowerPage();
                return
            }
            sers().userSrv.addPower(-1)
            mgrs().gameMgr.enterMode(GAME_MODE.Paidui,true);
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('paidui')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('paiduiBtn').getChildByName('icon').active = false

                if(sers().userSrv.power<=0){
                    sers().uiSrv.showUserGetPowerPage();
                    return
                }
                sers().userSrv.addPower(-1)
                mgrs().gameMgr.enterMode(GAME_MODE.Paidui,true);
            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁排队打麻将',
              },'common_video');
        }
    
    }

    peidui(){
        mgrs().soundMgr.playBtnSound();

        // let UserData = sers().userSrv.getUserData()
        // if((window['tt']||window['wx']) && UserData.maxLevel<8){
        //     sers().uiSrv.showMessage(`达到${this.jieduanName[7]}段位，解锁该模式`)
        //     return 
        // }

        // mgrs().gameMgr.enterMode(GAME_MODE.Paidui,true);
        // return

        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('Fangkuai')>=0){

            if(sers().userSrv.power<=0){
                sers().uiSrv.showUserGetPowerPage();
                return
            }
            sers().userSrv.addPower(-1)
            mgrs().gameMgr.enterMode(GAME_MODE.Fangkuai,true);
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('Fangkuai')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('newBtn').getChildByName('icon').active = false

                if(sers().userSrv.power<=0){
                    sers().uiSrv.showUserGetPowerPage();
                    return
                }
                sers().userSrv.addPower(-1)
                mgrs().gameMgr.enterMode(GAME_MODE.Fangkuai,true);
            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁麻将翻大饼',
              },'common_video');
        }
    
    }

    liushui(){
        mgrs().soundMgr.playBtnSound();

        // let UserData = sers().userSrv.getUserData()
        // if((window['tt']||window['wx']) && UserData.maxLevel<7){
        //     sers().uiSrv.showMessage(`达到${this.jieduanName[6]}段位，解锁该模式`)
        //     return 
        // }

        // mgrs().gameMgr.enterMode(GAME_MODE.Liushui,true);
        // return

        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('liushui')>=0){
            mgrs().gameMgr.enterMode(GAME_MODE.Liushui,true);
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('liushui')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('liushuiBtn').getChildByName('icon').active = false
                mgrs().gameMgr.enterMode(GAME_MODE.Liushui,true);

            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁流水席麻将',
              },'common_video');
        }
    
    }

    lingxiangzi(){
        mgrs().soundMgr.playBtnSound();


        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('lingmajiang')>=0){
            mgrs().gameMgr.enterMode(GAME_MODE.moveBrick,true);
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('lingmajiang')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('lingmajiangBtn').getChildByName('icon').active = false
                mgrs().gameMgr.enterMode(GAME_MODE.moveBrick,true);

            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁拎麻将',
              },'common_video');
        }

        
    }

    daxigua(){
        mgrs().soundMgr.playBtnSound();

        let game = sers().userSrv.getTiyanGame()
        if(game.indexOf('HechengDaxigua')>=0 || Number(sers().localStorageSrv.get(UserService.changwanModel)) == 1){
            // if(sers().userSrv.power<=0){
            //     sers().uiSrv.showUserGetPowerPage();
            //     return
            // }
            // sers().userSrv.addPower(-1)
            // mgrs().gameMgr.enterMode(GAME_MODE.HechengDaxigua,true);
            sers().uiSrv.showModeSelectPage()
        }else{
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                game.push('HechengDaxigua')
                sers().userSrv.setTiyanGame(game)
                this.node.getChildByName('majianghechengBtn').getChildByName('icon').active = false

                // if(sers().userSrv.power<=0){
                //     sers().uiSrv.showUserGetPowerPage();
                //     return
                // }
                // sers().userSrv.addPower(-1)
                // mgrs().gameMgr.enterMode(GAME_MODE.HechengDaxigua,true);
                sers().uiSrv.showModeSelectPage()

            }, (err) => {
            }, null, {
                scene: '解锁游戏',
                event: '解锁麻将合成',
              },'common_video');
        }

        
    }


    // showShopping() {
    //     mgrs().soundMgr.playBtnSound();
    //     sers().uiSrv.showShoppingPage()
    // }

    qiandao(){
        window['qiandao']=true
        mgrs().soundMgr.playBtnSound();
        sers().uiSrv.showSignInPage()
    }

    zhuti(){
        mgrs().soundMgr.playBtnSound();
        sers().uiSrv.showZhutiListPage()
    }

    showRank(){
        mgrs().soundMgr.playBtnSound();

        if(window['wx']){
            sers().uiSrv.showRankingListPage();
            return
        }

        let diquData = sers().userSrv.getUserData().city
        if (diquData == null || diquData == '') {
            let diquTemp = {
                continueCall: (() => {
                    // let diquData = sers().userSrv.getUserData().city
                    // this.renewDiQuName(diquData.cityName);
                    sers().uiSrv.showRankingListPage();
                }),
                closeCall: (() => {
                    // sers().uiSrv.showRankingListPage();
                }),
            }
            sers().uiSrv.showSelectDiQuPage(diquTemp);
            return;
        }

        sers().uiSrv.showRankingListPage();
    }

     /** 更新数据 */
     renewData() {
        let diquName = sers().userSrv.getUserData().city
        if (diquName == null) {
            this.renewDiQuName("");
        }
        else {
            this.renewDiQuName(diquName.cityName);
        }
    }
    

      /**
     *  加载分包资源 主要是预加载预制体 创建对象池
     */
      protected loadLevelScene() {
        // Loader.loadBundle("Scene", (res) => {
        //     Loader.loadBundleDir("Scene", "SinglePrefab", (res) => {
        //         for (let i = res.length - 1; i >= 0; --i) {
        //             let r = res[i];
        //             GlobalPool.createPool(r.name, r, r.name);
        //         }
        //     }, cc.Prefab, true);
        // }, true, true);
        // Loader.loadBundle("LevelScene", null, false, false);
        // Loader.loadBundle("LevelScene2", null, false, false);
        // Loader.loadBundle("LevelScene3", null, false, false);
      
    }

    isMoveTop = false
    curDingWei = -1
     /** 更新定位的显示 */
     renewDingWeiShow(isMoveTop: boolean) {
        this.isMoveTop = isMoveTop;
        this.node.getChildByName('wodeweizhi').getChildByName('wode').active = true
        this.node.getChildByName('wodeweizhi').getChildByName('top').active = false
        if (isMoveTop) {
            // this.dingweiLabel.string = `返回顶部`;
            this.node.getChildByName('wodeweizhi').getChildByName('wode').active = false
            this.node.getChildByName('wodeweizhi').getChildByName('top').active = true
        }
        else {
            // let diquName = GameDataHelp.getCurDiQuData();
            let diquData = sers().userSrv.getUserData().city
            if (diquData == null || diquData == '') {
                this.dingweiLabel.string = `未选地区`;
                return;
            }
            let duanwei = ''
            let UserData = sers().userSrv.getUserData()
            if(UserData.maxLevel>=8){
                duanwei = '·大师'
            }
            if(UserData.maxLevel >=11){
                duanwei = '·雀神'
            }
            
            this.dingweiLabel.string = `${diquData.cityName+duanwei} 地区排名:第${diquData.rank}名`;
        }
    }

      /** 定位功能 */
      dingweiEvent() {
        let diquData = sers().userSrv.getUserData().city
        if (diquData == null || diquData == '') {
            let diquTemp = {
                continueCall: (() => {
                    // let diquData = sers().userSrv.getUserData().city
                    // this.renewDiQuName(diquData.cityName);
                }),
                closeCall: (() => {
                    let diquData = sers().userSrv.getUserData().city
                    if(diquData){
                        this.renewDiQuName(diquData.cityName);
                    }
                }),
            }
            sers().uiSrv.showSelectDiQuPage(diquTemp);
            return;
        }
        mgrs().soundMgr.playSound('click');
        this.scrollView.getComponent(ScrollViewExample).moveShiTuToPos(this.curDingWei);
    }

     /** 更新地区排名 */
     renewDiQuName(diquName: string) {
        let data = this.RankMgr.getRankInfo();
        // cc.log(data);
        if (diquName == "") {
            cc.log("未选择地区");
            this.dingweiLabel.string = "未选择地区";
            return;
        }
        else {
            let curPaiMing: number = -1;
            for (let i = 0; i < data.cityRankInfo.length; i++) {
                if (diquName == data.cityRankInfo[i].cityName) {
                    curPaiMing = i + 1;
                    this.curDingWei = curPaiMing - 1;
                    // GameDataHelp.setCurDiQuData(data.cityRankInfo[i]);
                    break;
                }
            }
            // this.diquPaiMing.string = `我的地区排名：第${curPaiMing}名`;
            // this.dingweiLabel.string = `${diquName}`;
            let diquData = sers().userSrv.getUserData().city
            this.dingweiLabel.string = `${diquData.cityName}    地区排名:第${curPaiMing}名`;
        }
    }


   

 
    // update (dt) {}
}
